﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Collections;
using Catering.View_Operaction;
using Microsoft.Office.Core;
using System.IO;

namespace Catering.Catering_Page.Caipin
{
    public partial class Shipu_Week_List : System.Web.UI.Page
    {
        Catering.View_Operaction_Common voc = new View_Operaction_Common();
        public DataTable dt_Food = new DataTable();
        public DataTable DishList = new DataTable();
        public string[] strWeek = new string[] { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" };

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Txt_Date.Attributes.Add("onfocus", "WdatePicker({dateFmt:'yyyy-MM'})");
                this.LoadData();
            }
        }

        //加载页面数据
        public void LoadData()
        {
            if (Session["User"] != null)
            {
                string userid = Session["PersonnelID"].ToString();
                int companyid = 0;
                int groupid = 0;
                int classid = 0;
                bool isAdmin = false;
                Bind_Data_to_Controls.GetCompanyByCurrentUser(userid, out companyid, out groupid, out classid, out isAdmin);
                if (isAdmin)
                {
                    voc.DropDownListDataBind_Group(Dr_Operaction, companyid);
                    voc.DropDownListDataBind_Class(Dr_Class, Dr_Operaction.Items[0].Value);
                }
                else
                {
                    Bind_Data_to_Controls.Bind_Area_ddl(Dr_Operaction, isAdmin, groupid, companyid);
                    Bind_Data_to_Controls.Bind_Class_ddl(Dr_Operaction.SelectedItem, Dr_Class, isAdmin, classid);
                }
            }
            DateTime dtime = GetDateTime();
            if (dtime != null && dtime > DateTime.MinValue)
            {
                this.LoadZouDrop(dtime.Year, dtime.Month);
            }
        }

        //计算周期
        public void LoadZouDrop(int y, int M)
        {
            this.dr_select_Week.Items.Clear();
            //每月天数数组
            int[] daysMonth = new int[] { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
            daysMonth[1] = (0 == y % 4 && (y % 100 != 0 || y % 400 == 0)) ? 29 : 28;

            //总天数
            int daycount = daysMonth[M - 1];

            //得到1号对应的星期
            string strDatetime = y.ToString() + "-" + M.ToString() + "-01";
            int w = this.GetWeekInt(Convert.ToDateTime(strDatetime).DayOfWeek);

            int bctianshu = 0;//要想填充一个完整的table  需要补充的天数

            if (w == 1)
            {//判断1号是否是星期一
                if ((daycount % 7) == 0)
                {//判断是否能被星期整除
                    int zhouCount = daycount / 7;
                    for (int i = 1; i <= zhouCount; i++)
                    {
                        ListItem item = new ListItem();
                        item.Text = "第" + i.ToString() + "周";
                        item.Value = y.ToString() + "-" + M.ToString() + "-" + (((i - 1) * 7) + 1).ToString() + "|" + y.ToString() + "-" + M.ToString() + "-" + (i * 7).ToString();
                        this.dr_select_Week.Items.Add(item);
                    }
                }
                else
                {
                    int zhouCount = daycount / 7;
                    bctianshu = 7 - (daycount % 7); //需要补充的天数
                    for (int i = 1; i <= zhouCount; i++)
                    {
                        ListItem item = new ListItem();
                        item.Text = "第" + i.ToString() + "周";
                        item.Value = y.ToString() + "-" + M.ToString() + "-" + (((i - 1) * 7) + 1).ToString() + "|" + y.ToString() + "-" + M.ToString() + "-" + (i * 7).ToString();
                        this.dr_select_Week.Items.Add(item);
                    }
                    ListItem ite = new ListItem();
                    ite.Text = "第" + (zhouCount + 1).ToString() + "周";
                    if (M != 12)
                    {
                        ite.Value = y.ToString() + "-" + M.ToString() + "-" + ((zhouCount * 7) + 1).ToString() + "|" + y.ToString() + "-" + (M + 1).ToString() + "-" + bctianshu.ToString();
                    }
                    else
                    {
                        ite.Value = y.ToString() + "-" + M.ToString() + "-" + ((zhouCount * 7) + 1).ToString() + "|" + (y + 1).ToString() + "-" + "01" + "-" + bctianshu.ToString();
                    }
                    this.dr_select_Week.Items.Add(ite);
                }
            }
            else
            {
                int dygxingqiyi = ((w == 0) ? 1 : (8 - w)); //距离下一个星期一还有几天
                if (((daycount - dygxingqiyi) % 7) == 0)
                {
                    int zhouCount = (daycount - dygxingqiyi) / 7;
                    for (int i = 1; i <= zhouCount; i++)
                    {
                        ListItem item = new ListItem();
                        item.Text = "第" + i.ToString() + "周";
                        item.Value = y.ToString() + "-" + M.ToString() + "-" + (((i - 1) * 7) + dygxingqiyi + 1).ToString() + "|" + y.ToString() + "-" + M.ToString() + "-" + ((i * 7) + dygxingqiyi).ToString();
                        this.dr_select_Week.Items.Add(item);
                    }
                }
                else
                {
                    bctianshu = 7 - ((daycount - dygxingqiyi) % 7); //需要补充的天数
                    int zhouCount = (daycount - dygxingqiyi) / 7;
                    for (int i = 1; i <= zhouCount; i++)
                    {
                        ListItem item = new ListItem();
                        item.Text = "第" + i.ToString() + "周";
                        item.Value = y.ToString() + "-" + M.ToString() + "-" + (((i - 1) * 7) + dygxingqiyi + 1).ToString() + "|" + y.ToString() + "-" + M.ToString() + "-" + ((i * 7) + dygxingqiyi).ToString();
                        this.dr_select_Week.Items.Add(item);
                    }
                    ListItem ite = new ListItem();
                    ite.Text = "第" + (zhouCount + 1).ToString() + "周";
                    if (M != 12)
                    {
                        ite.Value = y.ToString() + "-" + M.ToString() + "-" + ((zhouCount * 7) + dygxingqiyi + 1).ToString() + "|" + y.ToString() + "-" + (M + 1).ToString() + "-" + bctianshu.ToString();
                    }
                    else
                    {
                        ite.Value = y.ToString() + "-" + M.ToString() + "-" + ((zhouCount * 7) + dygxingqiyi + 1).ToString() + "|" + (y + 1).ToString() + "-" + "01" + "-" + bctianshu.ToString();
                    }
                    this.dr_select_Week.Items.Add(ite);

                }
            }
        }

        //获取周对应的值
        public int GetWeekInt(DayOfWeek week)
        {
            switch (week)
            {
                case DayOfWeek.Monday://星期一
                    return 1;
                    break;
                case DayOfWeek.Tuesday://星期二
                    return 2;
                    break;
                case DayOfWeek.Wednesday://星期三
                    return 3;
                    break;
                case DayOfWeek.Thursday://星期四
                    return 4;
                    break;
                case DayOfWeek.Friday://星期五
                    return 5;
                    break;
                case DayOfWeek.Saturday://星期六
                    return 6;
                    break;
                case DayOfWeek.Sunday://星期日
                    return 0;
                    break;
                default:
                    return -1;
                    break;
            }
        }

        //加载对应的菜
        public void LoadDishByWeek(string strWeek, string FoodID)
        {
            DateTime time = this.GetWeekTime(strWeek);
            this.DishList.Clear();
            if (time > DateTime.MinValue)
                this.DishList = new Catering_Rules.T_RecipeInformation().GetWeekList(this.Dr_Class.SelectedValue, FoodID, time.ToShortDateString()).Tables[0];
        }

        //获取菜名称
        public string GetDishName(string cid)
        {
            Catering_Model.E_Dish md = new Catering_Rules.T_Dish().GetModel(Convert.ToInt32(cid));
            return md == null ? "" : md.Name;
        }

        //获取周对应的日期
        public DateTime GetWeekTime(string strWeek)
        {
            string strTime = this.dr_select_Week.SelectedValue;
            if (string.IsNullOrEmpty(strTime) || strTime == "选择周") return DateTime.MinValue;
            DateTime startTime = Convert.ToDateTime(strTime.Split('|')[0]);
            DateTime endTime = Convert.ToDateTime(strTime.Split('|')[1]);
            DateTime time = DateTime.Now;
            for (DateTime dtime = startTime; dtime <= endTime; dtime = dtime.AddDays(1))
            {
                if (dtime.DayOfWeek.ToString() == strWeek)
                {
                    time = dtime;
                }
            }
            return time;
        }

        //查询周食谱
        public void but_Seach_Click(object sender, EventArgs e)
        {
            this.txt_danwei.Text = "";
            this.txt_riqi.Text = "";
            this.txt_banben.Text = "";
            this.txt_shoukonghao.Text = "";

            this.dt_Food = new Catering_Rules.FoodMealType().GetList(" id<>5 and id<>6 ").Tables[0];
            string groupid = Dr_Operaction.SelectedValue;
            string classid = Dr_Class.SelectedValue;
            string riqi = dr_select_Week.SelectedValue;
            string[] splitriqi = riqi.Split('|');
            DateTime starttime = DateTime.MinValue;
            DateTime endtime = DateTime.MinValue;
            if (groupid == "-10" || classid == "-10" || riqi == "选择周") return;
            Catering_Model.OperationArea tempgroup = new Catering_Rules.OperationArea().GetModel(Convert.ToInt32(groupid));
            Catering_Model.ClassInfo tempclass = new Catering_Rules.ClassInfo().GetModel(Convert.ToInt32(classid));
            if (splitriqi.Length == 2)
            {
                DateTime.TryParse(splitriqi[0], out starttime);
                DateTime.TryParse(splitriqi[1], out endtime);
            }
            if (tempgroup != null && tempclass != null && starttime > DateTime.MinValue && endtime > DateTime.MinValue)
            {
                this.txt_danwei.Text = tempclass.temp1;
                this.txt_riqi.Text = starttime.ToString("yyyy年MM月dd日") + "—" + endtime.ToString("yyyy年MM月dd日");
                int companyid = 0;
                string controlled = "";
                string vs = "";
                Int32.TryParse(tempgroup.temp2, out companyid);
                if (companyid > 0)
                {
                    Catering_Model.Company com = new Catering_Rules.Company().GetModel(companyid);
                    if (com != null && !string.IsNullOrEmpty(com.Controlled) && !string.IsNullOrEmpty(com.Vs))
                    {
                        controlled = com.Controlled;
                        vs = com.Vs;
                    }
                }
                this.txt_banben.Text = vs;
                this.txt_shoukonghao.Text = controlled;
            }

        }

        protected void Dr_Operaction_SelectedIndexChanged(object sender, EventArgs e)
        {
            voc.DropDownListDataBind_Class(Dr_Class, Dr_Operaction.SelectedValue);
        }

        //根据年月加载周
        protected void dr_Moth_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        //导出Excel
        protected void but_out_Excel_Click(object sender, EventArgs e)
        {
            Microsoft.Office.Interop.Excel.Application excel1 = null;
            Microsoft.Office.Interop.Excel._Worksheet ws = null;
            Microsoft.Office.Interop.Excel.Range canbie = null;
            string stick = DateTime.Now.Ticks.ToString();

            try
            {
                excel1 = new Microsoft.Office.Interop.Excel.Application();
                excel1.Application.Workbooks.Add(true);//引用Excel工作簿
                //Microsoft.Office.Interop.Excel._Worksheet ws = new Microsoft.Office.Interop.Excel.WorksheetClass();
                ws = new Microsoft.Office.Interop.Excel.WorksheetClass();
                ws = (Microsoft.Office.Interop.Excel._Worksheet)excel1.ActiveSheet;//获取当前活动工作薄
                //Microsoft.Office.Interop.Excel.Range canbie;//创建Range操作一行作为标题
                excel1.Visible = false;

                #region  表头

                string riqi = dr_select_Week.SelectedValue;
                string[] splitriqi = riqi.Split('|');
                DateTime starttime = DateTime.MinValue;
                DateTime.TryParse(splitriqi[0], out starttime);
                int zhouth = 1;
                if (starttime > DateTime.MinValue)
                {
                    System.Globalization.GregorianCalendar gc = new System.Globalization.GregorianCalendar();
                    zhouth = gc.GetWeekOfYear(DateTime.Now, System.Globalization.CalendarWeekRule.FirstDay, DayOfWeek.Monday);
                }
                canbie = ws.get_Range(ws.Cells[1, 1], ws.Cells[1, 8]);
                canbie.MergeCells = true;//合并单元格
                canbie.HorizontalAlignment = XlVAlign.xlVAlignCenter;//居中
                canbie.Font.Bold = 2;
                ws.Cells[1, 1] = "第" + zhouth + "周食谱清单";

                canbie = ws.get_Range(ws.Cells[2, 1], ws.Cells[2, 8]);
                canbie.MergeCells = true;//合并单元格
                ws.Cells[2, 1] = "单位:" + this.txt_danwei.Text + "　　日期:" + this.txt_riqi.Text + "　　版本:" + this.txt_banben.Text + "　　受控号:" + this.txt_shoukonghao.Text;

                #endregion

                #region 第一行标题
                ws.Cells[3, 1] = "餐别";
                for (int i = 0; i < strWeek.Length; i++)
                {
                    string weekName = "";
                    switch (strWeek[i].ToString())
                    {
                        case "Monday":
                            weekName = "星期一";
                            break;
                        case "Tuesday":
                            weekName = "星期二";
                            break;
                        case "Wednesday":
                            weekName = "星期三";
                            break;
                        case "Thursday":
                            weekName = "星期四";
                            break;
                        case "Friday":
                            weekName = "星期五";
                            break;
                        case "Saturday":
                            weekName = "星期六";
                            break;
                        case "Sunday":
                            weekName = "星期日";
                            break;
                    }
                    ws.Cells[3, i + 2] = weekName;
                }
                #endregion
                int canbiehangshu = 4;//餐别行数
                this.dt_Food = new Catering_Rules.FoodMealType().GetList(" id<>5 and id<>6 ").Tables[0];
                foreach (System.Data.DataRow row in this.dt_Food.Rows)
                {
                    int xingbieleibie = 2;//星期列数
                    for (int j = 0; j < this.strWeek.Length; j++)
                    {
                        string rowid = row["id"].ToString() == "4" ? "2" : row["id"].ToString();
                        this.LoadDishByWeek(strWeek[j], rowid);
                        if (this.DishList != null && this.DishList.Rows.Count > 0)
                        {
                            int lie = canbiehangshu;
                            int zao = 0;
                            int qita = 0;
                            foreach (System.Data.DataRow row_dish in this.DishList.Rows)
                            {
                                if (row_dish["FMID"].ToString() == "1")
                                {
                                    if (zao == 3) break;
                                    if (row_dish["youxian"].ToString() == "1")
                                    {
                                        zao++;
                                        ws.Cells[lie, xingbieleibie] = row_dish["Name"].ToString().Replace('N', ' ').Trim();
                                        lie += 1;
                                    }
                                }
                                else if (qita < 6)
                                {
                                    qita++;
                                    ws.Cells[lie, xingbieleibie] = row_dish["Name"].ToString().Replace('N', ' ').Trim();
                                    lie += 1;
                                }
                            }
                        }
                        xingbieleibie += 1;
                    }
                    int nRowNum = canbiehangshu;
                    if (row["id"].ToString() == "1")
                    {
                        nRowNum = canbiehangshu + 2;
                    }
                    else
                    {
                        nRowNum = canbiehangshu + 5;
                    }

                    canbie = ws.get_Range(ws.Cells[nRowNum, 1], ws.Cells[canbiehangshu, 1]); //取得合并的区域
                    canbie.MergeCells = true;//合并单元格 
                    ws.Cells[canbiehangshu, 1] = row["FMName"].ToString();
                    canbiehangshu = nRowNum + 1;
                }
                ws.Cells.EntireColumn.AutoFit();
                canbie = ws.get_Range(ws.Cells[3, 1], ws.Cells[canbiehangshu - 1, 8]);
                canbie.Borders.LineStyle = 1;

                #region 底部

                canbie = ws.get_Range(ws.Cells[canbiehangshu, 1], ws.Cells[canbiehangshu, 8]);
                canbie.MergeCells = true;//合并单元格 
                ws.Cells[canbiehangshu, 1] = "制作人：　　　　　　　　审核人：　　　　　　　　批准人：";

                #endregion

                if (!Directory.Exists(Server.MapPath("../../xls_template"))) Directory.CreateDirectory(Server.MapPath("../../xls_template"));
                ws.SaveAs(Server.MapPath("../../xls_template") + "\\" + stick + ".xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlAddIn8);

            }
            finally
            {
                if (excel1 != null)
                {
                    if (ws != null)
                    {
                        if (canbie != null)
                        {
                            System.Runtime.InteropServices.Marshal.ReleaseComObject(canbie);
                            canbie = null;

                        }
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(ws);
                        ws = null;
                    }
                }
                excel1.Application.Workbooks.Close();
                excel1.Quit();
                System.Runtime.InteropServices.Marshal.ReleaseComObject(excel1);
                Toolss.KillExcel(excel1);
                excel1 = null;
                GC.Collect();
            }

            #region 发送

            try
            {
                string path = Server.MapPath("../../xls_template") + "\\" + stick + ".xls";
                System.IO.FileInfo file = new System.IO.FileInfo(path);
                Response.Clear();
                Response.Charset = "GB2312";
                Response.ContentEncoding = System.Text.Encoding.UTF8;
                // 添加头信息，,弹出另存为窗口  
                Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(file.Name));
                //让浏览器头显示下载信息  
                Response.AddHeader("Content-Length", file.Length.ToString());
                // 指定返回一个不能被客户端读取的流，下载  
                Response.ContentType = "application/ms-excel";
                //把文件流下载到客户端  
                Response.WriteFile(file.FullName);
                // 停止页面的执行
                Response.End();
            }
            catch { }

            #endregion

        }

        protected void Txt_Date_TextChanged(object sender, EventArgs e)
        {

            DateTime dtime = GetDateTime();
            if (dtime != null && dtime > DateTime.MinValue)
            {
                this.LoadZouDrop(dtime.Year, dtime.Month);
            }
        }

        public DateTime GetDateTime()
        {
            DateTime dtime = DateTime.MinValue;
            string strDate = this.Txt_Date.Text.Trim();
            if (!string.IsNullOrEmpty(strDate)) DateTime.TryParse(strDate, out dtime);
            return dtime;
        }
    }
}